/**
 * Created by lixinkun on 2017/7/8.
 */
'use stric';
import * as TYPES from './actionTypes';
import fetchUrl from '../constants/fetchUrl';
import fetchWithTimeout from '../utils/fetchWithTimeout';
import Toast from 'react-native-root-toast';
import px2dp from '../utils/px2dp';

//内部方法
function requestData() {
    return{
        type: TYPES.FETCH_PLACE_DATA_REQUEST,
    };
}

function receiveData(json) {
    return {
        type: TYPES.FETCH_PLACE_DATA_SUCCESS,
        dataSource: json,
    };
}

function fetchFailure() {
    return {
        type: TYPES.FETCH_PLACE_DATA_FAILURE,
    };
}

function isValidData(responseData) {
    if (responseData.length > 0) {
        return true;
    } else {
        return false;
    }
}

/**
 * 外部调用这个方法去获取数据
 * @returns {function(*=)}
 */
export function fetchDataFromNet() {
    const url = fetchUrl.weatherBaseUrl + 'china';
    function fetchPlaceData(dispatch) {
        fetchWithTimeout(5000, fetch(url)
            .then((response) =>{console.log(response);return response.json()})
            .then((json) => {
                if (isValidData(json)) {
                    dispatch(receiveData(json));
                } else {
                    dispatch(fetchFailure());
                }
            }).catch((error) => {
                console.log(error);
                Toast.show('获取数据失败', {position: px2dp(-80)});
            })
        );
    }
    return (
        dispatch => {
            dispatch(requestData());
            fetchPlaceData(dispatch);
        }
    )
}


/**
 * 获取本地数据，暂时不去实现
 */
export function onlyFetchLocalData() {

}

